<script setup lang="ts">
import type { LifecycleFacet, Transition } from '#/api/resource-center/types';

import { computed, reactive, ref } from 'vue';

import { IconifyIcon } from '@vben/icons';

import { message } from 'ant-design-vue';

// Props
interface Props {
  lifecycle?: LifecycleFacet;
}

const props = defineProps<Props>();

// Emits
const emit = defineEmits<{
  update: [lifecycle: LifecycleFacet];
}>();

// 响应式数据
const stateModalVisible = ref(false);
const transitionModalVisible = ref(false);
const transitionRuleModalVisible = ref(false);
const editingTransition = ref<null | Transition>(null);

// 表单数据
const stateForm = reactive({
  name: '',
  description: '',
});

const transitionForm = reactive({
  to: '',
  cause: '',
  context: '',
});

const transitionRuleForm = reactive({
  from: '',
  to: '',
  trigger: 'MANUAL',
  condition: '',
  actions: [] as any[],
});

// 计算属性
const lifecycle = computed(
  () =>
    props.lifecycle || {
      currentState: '',
      machine: { states: [], initial: '', transitions: [] },
    },
);

// 表格列定义
const transitionColumns = [
  { title: '起始状态', dataIndex: 'from', key: 'from' },
  { title: '目标状态', dataIndex: 'to', key: 'to' },
  { title: '触发条件', dataIndex: 'trigger', key: 'trigger' },
  { title: '条件表达式', dataIndex: 'condition', key: 'condition' },
  { title: '操作', key: 'action', width: 120 },
];

// 方法
const getStateColor = (state: string) => {
  const colorMap: Record<string, string> = {
    DRAFT: 'default',
    ACTIVE: 'green',
    INACTIVE: 'orange',
    DEPRECATED: 'red',
    RETIRED: 'gray',
    AVAILABLE: 'blue',
    OCCUPIED: 'red',
    MAINTENANCE: 'orange',
    SERVING: 'purple',
    OFF_DUTY: 'gray',
  };
  return colorMap[state] || 'default';
};

const showStateModal = () => {
  stateModalVisible.value = true;
};

const addState = () => {
  if (!stateForm.name) {
    message.error('请输入状态名称');
    return;
  }

  const newStates = [...(lifecycle.value.machine.states || []), stateForm.name];
  const newMachine = {
    ...lifecycle.value.machine,
    states: newStates,
    initial: lifecycle.value.machine.initial || stateForm.name,
  };

  emit('update', {
    ...lifecycle.value,
    machine: newMachine,
  });

  message.success('状态添加成功');
  stateModalVisible.value = false;
  resetStateForm();
};

const cancelState = () => {
  stateModalVisible.value = false;
  resetStateForm();
};

const resetStateForm = () => {
  stateForm.name = '';
  stateForm.description = '';
};

const setInitialState = (state: string) => {
  const newMachine = {
    ...lifecycle.value.machine,
    initial: state,
  };

  emit('update', {
    ...lifecycle.value,
    machine: newMachine,
  });

  message.success('初始状态设置成功');
};

const removeState = (state: string) => {
  if (state === lifecycle.value.machine.initial) {
    message.error('不能删除初始状态');
    return;
  }

  const newStates = lifecycle.value.machine.states.filter((s) => s !== state);
  const newTransitions = lifecycle.value.machine.transitions.filter(
    (t) => t.from !== state && t.to !== state,
  );

  const newMachine = {
    ...lifecycle.value.machine,
    states: newStates,
    transitions: newTransitions,
  };

  emit('update', {
    ...lifecycle.value,
    machine: newMachine,
  });

  message.success('状态删除成功');
};

const showTransitionModal = () => {
  transitionModalVisible.value = true;
};

const executeTransition = () => {
  if (!transitionForm.to) {
    message.error('请选择目标状态');
    return;
  }

  emit('update', {
    ...lifecycle.value,
    currentState: transitionForm.to,
  });

  message.success('状态转换成功');
  transitionModalVisible.value = false;
  resetTransitionForm();
};

const cancelTransition = () => {
  transitionModalVisible.value = false;
  resetTransitionForm();
};

const resetTransitionForm = () => {
  transitionForm.to = '';
  transitionForm.cause = '';
  transitionForm.context = '';
};

const showTransitionRuleModal = () => {
  editingTransition.value = null;
  resetTransitionRuleForm();
  transitionRuleModalVisible.value = true;
};

const editTransition = (transition: Transition) => {
  editingTransition.value = transition;
  transitionRuleForm.from = transition.from;
  transitionRuleForm.to = transition.to;
  transitionRuleForm.trigger = transition.trigger;
  transitionRuleForm.condition = transition.condition || '';
  transitionRuleForm.actions = transition.actions || [];
  transitionRuleModalVisible.value = true;
};

const saveTransitionRule = () => {
  if (!transitionRuleForm.from || !transitionRuleForm.to) {
    message.error('请选择起始状态和目标状态');
    return;
  }

  const newTransition: Transition = {
    from: transitionRuleForm.from,
    to: transitionRuleForm.to,
    trigger: transitionRuleForm.trigger,
    condition: transitionRuleForm.condition,
    actions: transitionRuleForm.actions,
  };

  const currentTransitions = lifecycle.value.machine.transitions || [];
  let newTransitions: Transition[];

  if (editingTransition.value) {
    // 编辑模式
    newTransitions = currentTransitions.map((t) =>
      t === editingTransition.value ? newTransition : t,
    );
  } else {
    // 新增模式
    newTransitions = [...currentTransitions, newTransition];
  }

  const newMachine = {
    ...lifecycle.value.machine,
    transitions: newTransitions,
  };

  emit('update', {
    ...lifecycle.value,
    machine: newMachine,
  });

  message.success(
    editingTransition.value ? '转换规则更新成功' : '转换规则添加成功',
  );
  transitionRuleModalVisible.value = false;
  resetTransitionRuleForm();
};

const cancelTransitionRule = () => {
  transitionRuleModalVisible.value = false;
  resetTransitionRuleForm();
};

const resetTransitionRuleForm = () => {
  transitionRuleForm.from = '';
  transitionRuleForm.to = '';
  transitionRuleForm.trigger = 'MANUAL';
  transitionRuleForm.condition = '';
  transitionRuleForm.actions = [];
};

const removeTransition = (transition: Transition) => {
  const newTransitions = lifecycle.value.machine.transitions.filter(
    (t) => t !== transition,
  );
  const newMachine = {
    ...lifecycle.value.machine,
    transitions: newTransitions,
  };

  emit('update', {
    ...lifecycle.value,
    machine: newMachine,
  });

  message.success('转换规则删除成功');
};

const addAction = () => {
  transitionRuleForm.actions.push({
    type: 'API_CALL',
    config: '',
  });
};

const removeAction = (index: number) => {
  transitionRuleForm.actions.splice(index, 1);
};
</script>

<template>
  <div class="resource-lifecycle">
    <!-- 当前状态 -->
    <div class="current-state">
      <a-card title="当前状态">
        <div class="state-info">
          <a-tag :color="getStateColor(lifecycle?.currentState)" size="large">
            {{ lifecycle?.currentState || '未设置' }}
          </a-tag>
          <a-button
            v-if="lifecycle?.machine?.states?.length"
            type="primary"
            @click="showTransitionModal"
          >
            状态转换
          </a-button>
        </div>
      </a-card>
    </div>

    <!-- 状态机配置 -->
    <div class="state-machine">
      <a-card title="状态机配置">
        <div class="machine-header">
          <a-button type="primary" @click="showStateModal">
            <template #icon>
              <IconifyIcon icon="ant-design:plus-outlined" />
            </template>
            添加状态
          </a-button>
          <a-button @click="showTransitionRuleModal">
            <template #icon>
              <LinkOutlined />
            </template>
            转换规则
          </a-button>
        </div>

        <!-- 状态列表 -->
        <div class="states-container">
          <a-empty
            v-if="!lifecycle?.machine?.states?.length"
            description="暂无状态定义"
          />

          <div v-else class="states-grid">
            <a-card
              v-for="state in lifecycle.machine.states"
              :key="state"
              class="state-card"
              :class="{ 'initial-state': state === lifecycle.machine.initial }"
            >
              <template #title>
                <div class="state-title">
                  <span>{{ state }}</span>
                  <a-tag
                    v-if="state === lifecycle.machine.initial"
                    color="green"
                    size="small"
                  >
                    初始状态
                  </a-tag>
                </div>
              </template>

              <div class="state-actions">
                <a-button
                  v-if="state !== lifecycle.machine.initial"
                  type="link"
                  size="small"
                  @click="setInitialState(state)"
                >
                  设为初始状态
                </a-button>
                <a-button
                  v-if="state !== lifecycle.machine.initial"
                  type="link"
                  size="small"
                  danger
                  @click="removeState(state)"
                >
                  删除
                </a-button>
              </div>
            </a-card>
          </div>
        </div>

        <!-- 转换规则列表 -->
        <div
          v-if="lifecycle?.machine?.transitions?.length"
          class="transitions-section"
        >
          <h4>转换规则</h4>
          <a-table
            :columns="transitionColumns"
            :data-source="lifecycle.machine.transitions"
            :pagination="false"
            size="small"
          >
            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'action'">
                <a-space>
                  <a-button
                    type="link"
                    size="small"
                    @click="editTransition(record)"
                  >
                    编辑
                  </a-button>
                  <a-button
                    type="link"
                    size="small"
                    danger
                    @click="removeTransition(record)"
                  >
                    删除
                  </a-button>
                </a-space>
              </template>
            </template>
          </a-table>
        </div>
      </a-card>
    </div>

    <!-- 添加状态模态框 -->
    <a-modal
      v-model:open="stateModalVisible"
      title="添加状态"
      @ok="addState"
      @cancel="cancelState"
    >
      <a-form :model="stateForm" layout="vertical">
        <a-form-item label="状态名称" name="name">
          <a-input
            v-model:value="stateForm.name"
            placeholder="请输入状态名称"
          />
        </a-form-item>
        <a-form-item label="状态描述" name="description">
          <a-textarea
            v-model:value="stateForm.description"
            placeholder="请输入状态描述"
          />
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 状态转换模态框 -->
    <a-modal
      v-model:open="transitionModalVisible"
      title="状态转换"
      @ok="executeTransition"
      @cancel="cancelTransition"
    >
      <a-form :model="transitionForm" layout="vertical">
        <a-form-item label="目标状态" name="to">
          <a-select
            v-model:value="transitionForm.to"
            placeholder="请选择目标状态"
          >
            <a-select-option
              v-for="state in lifecycle?.machine?.states"
              :key="state"
              :value="state"
            >
              {{ state }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="转换原因" name="cause">
          <a-input
            v-model:value="transitionForm.cause"
            placeholder="请输入转换原因"
          />
        </a-form-item>
        <a-form-item label="上下文" name="context">
          <a-textarea
            v-model:value="transitionForm.context"
            placeholder="请输入上下文信息（JSON格式）"
          />
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 转换规则模态框 -->
    <a-modal
      v-model:open="transitionRuleModalVisible"
      :title="editingTransition ? '编辑转换规则' : '添加转换规则'"
      width="800px"
      @ok="saveTransitionRule"
      @cancel="cancelTransitionRule"
    >
      <a-form :model="transitionRuleForm" layout="vertical">
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="起始状态" name="from">
              <a-select
                v-model:value="transitionRuleForm.from"
                placeholder="请选择起始状态"
              >
                <a-select-option
                  v-for="state in lifecycle?.machine?.states"
                  :key="state"
                  :value="state"
                >
                  {{ state }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="目标状态" name="to">
              <a-select
                v-model:value="transitionRuleForm.to"
                placeholder="请选择目标状态"
              >
                <a-select-option
                  v-for="state in lifecycle?.machine?.states"
                  :key="state"
                  :value="state"
                >
                  {{ state }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>

        <a-form-item label="触发条件" name="trigger">
          <a-select
            v-model:value="transitionRuleForm.trigger"
            placeholder="请选择触发条件"
          >
            <a-select-option value="MANUAL">手动触发</a-select-option>
            <a-select-option value="AUTO">自动触发</a-select-option>
            <a-select-option value="EVENT">事件触发</a-select-option>
            <a-select-option value="SCHEDULE">定时触发</a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item label="条件表达式" name="condition">
          <a-input
            v-model:value="transitionRuleForm.condition"
            placeholder="请输入条件表达式"
          />
        </a-form-item>

        <a-form-item label="转换动作" name="actions">
          <div class="actions-editor">
            <a-button @click="addAction" type="dashed" block>
              <IconifyIcon icon="ant-design:plus-outlined" />
              添加动作
            </a-button>

            <div v-if="transitionRuleForm.actions" class="actions-list">
              <div
                v-for="(action, index) in transitionRuleForm.actions"
                :key="index"
                class="action-item"
              >
                <a-row :gutter="8">
                  <a-col :span="6">
                    <a-select
                      v-model:value="action.type"
                      placeholder="动作类型"
                    >
                      <a-select-option value="API_CALL">
                        API调用
                      </a-select-option>
                      <a-select-option value="STATE_CHANGE">
                        状态变更
                      </a-select-option>
                      <a-select-option value="EVENT_EMIT">
                        事件发布
                      </a-select-option>
                      <a-select-option value="NOTIFICATION">
                        通知
                      </a-select-option>
                    </a-select>
                  </a-col>
                  <a-col :span="12">
                    <a-input
                      v-model:value="action.config"
                      placeholder="配置信息"
                    />
                  </a-col>
                  <a-col :span="4">
                    <a-button type="text" danger @click="removeAction(index)">
                      <IconifyIcon icon="ant-design:delete-outlined" />
                    </a-button>
                  </a-col>
                </a-row>
              </div>
            </div>
          </div>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<style lang="less" scoped>
.resource-lifecycle {
  .current-state {
    margin-bottom: 16px;

    .state-info {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
  }

  .state-machine {
    .machine-header {
      display: flex;
      gap: 8px;
      margin-bottom: 16px;
    }

    .states-container {
      .states-grid {
        display: grid;
        grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
        gap: 12px;
        margin-bottom: 16px;
      }

      .state-card {
        &.initial-state {
          border-color: #52c41a;
          background: #f6ffed;
        }

        .state-title {
          display: flex;
          justify-content: space-between;
          align-items: center;
        }

        .state-actions {
          display: flex;
          gap: 4px;
        }
      }
    }

    .transitions-section {
      h4 {
        margin: 0 0 12px 0;
        font-size: 14px;
        font-weight: 600;
      }
    }
  }

  .actions-editor {
    .actions-list {
      margin-top: 12px;

      .action-item {
        margin-bottom: 8px;
        padding: 8px;
        border: 1px solid #f0f0f0;
        border-radius: 4px;
        background: #fafafa;
      }
    }
  }
}
</style>
